import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";

// 定义天气数据类型
interface WeatherInfo {
    temperature: number;
    condition: string;
    humidity: number;
    windSpeed: number;
}

// 模拟城市天气数据
const weatherData = {
    "北京": { temperature: 20, condition: "晴朗", humidity: 45, windSpeed: 8 },
    "上海": { temperature: 25, condition: "多云", humidity: 60, windSpeed: 12 },
    "广州": { temperature: 28, condition: "小雨", humidity: 75, windSpeed: 6 },
    "深圳": { temperature: 27, condition: "阴天", humidity: 70, windSpeed: 10 },
    "杭州": { temperature: 22, condition: "多云", humidity: 65, windSpeed: 9 }
} as const satisfies Record<string, WeatherInfo>;

// 模拟函数调用和数据返回
function getWeatherInfo(city: string): { content: Array<{ type: "text"; text: string }> } {
    const weather = weatherData[city as keyof typeof weatherData];
    
    if (!weather) {
        const availableCities = Object.keys(weatherData).join("、");
        return {
            content: [{
                type: "text",
                text: `未找到城市 ${city} 的天气信息。支持的城市包括：${availableCities}`
            }]
        };
    }

    // 模板字符串格式
    const weatherText = `${city}的天气信息：
        温度：${weather.temperature}°C
        天气：${weather.condition}
        湿度：${weather.humidity}%
        风速：${weather.windSpeed}m/s`.replace(/^\s+/gm, "");  // 使用正则移除行首空格
    return {
        content: [{
            type: "text",
            text: weatherText
        }]
    };
}

// 创建 MCP 服务器
const server = new McpServer({
    name: "weather-server",
    version: "1.0.0",
    description: "城市天气信息服务"
});

// 注册天气查询工具
server.tool(
    "get-weather",
    "获取指定城市的天气信息",
    {
        city: z.string().describe("城市名称（如：北京、上海、广州、深圳）")
    },
    async ({ city }) => {
        return getWeatherInfo(city);
    }
);

// 启动服务器
async function main() {
    const transport = new StdioServerTransport();
    await server.connect(transport);
}

main().catch((error) => {
    console.error("初始化失败:", error);
    process.exit(1);
});
